/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.haiberg.osgi.bundle.reportcaller.servlet;

import com.haiberg.osgi.bundle.reportservice.ReportExportInfo;
import com.haiberg.osgi.bundle.reportservice.ReportFileHandler;
import com.haiberg.osgi.bundle.reportservice.ReportParamValue;
import com.haiberg.osgi.bundle.reportservice.ReportRequestHandler;
import com.haiberg.osgi.bundle.reportservice.type.ReportParamType;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

/**
 *
 * @author gyue
 */
public class ReportServlet extends HttpServlet{

    public ReportServlet(){}
    
    BundleContext context = null;
    ServiceReference<ReportRequestHandler> serviceReference;
    ServiceReference<ReportFileHandler> reportFileServiceReference;
    public ReportServlet(BundleContext context){
        this.context = context;
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String reportName = req.getParameter("reportName");
        ReportFileHandler reportFileHandler = getReportFileHandler();
        System.out.println("new report file handler");
        System.out.println(reportFileHandler);
        ReportRequestHandler requestHandler = getReportRequestHandler();
        System.out.println(requestHandler);
        if(requestHandler != null){
            ReportExportInfo exportInfo = new ReportExportInfo();
            exportInfo.setDbUsername("");
            exportInfo.setDbUserpwd("");
            exportInfo.setExportFormat(0);
            exportInfo.setReportName("tcp://"+reportName+".rpt");
            List<ReportParamValue> params = generateTestParams();
            exportInfo.setParams(params);
            requestHandler.setExportInfo(exportInfo);
                
            InputStream is = null;
            OutputStream os = null;
            try {
                is = requestHandler.getReportDataAsStream();
                
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + reportName +".pdf\"");
                resp.setHeader("Content-Length" ,""+is.available());
                os = resp.getOutputStream();
                
                byte[] cache = new byte[1024];
                int len = 0;
                while((len = is.read(cache)) != -1){
                    os.write(cache, 0, len);
                }
            } catch (Exception ex) {
                Logger.getLogger(ReportServlet.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if(is != null){
                    try {
                        is.close();
                    } catch (IOException ex) {
                        Logger.getLogger(ReportServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if(os != null){
                    os.close();
                }
            }
        }
    }
    
    private List<ReportParamValue> generateTestParams(){
        List<ReportParamValue> params = new ArrayList<ReportParamValue>();
        ReportParamValue storeid = new ReportParamValue(1, "storeid", "234", ReportParamType.INT.getType());
        params.add(storeid);
        ReportParamValue region = new ReportParamValue(2, "region", "region", ReportParamType.DEFAULTS.getType());
        params.add(region);
        
        return params;
    }
    
    public ReportRequestHandler getReportRequestHandler(){
        if(serviceReference != null){
            return this.context.getService(serviceReference);
        }else if(this.context != null){
            serviceReference = (ServiceReference<ReportRequestHandler>) this.context.getServiceReference(ReportRequestHandler.class.getName());
            return this.context.getService(serviceReference);
        }
        return null;
    }
    
    public ReportFileHandler getReportFileHandler(){
        if(reportFileServiceReference != null){
            return this.context.getService(reportFileServiceReference);
        }else if(this.context != null){
            reportFileServiceReference = (ServiceReference<ReportFileHandler>) this.context.getServiceReference(ReportFileHandler.class.getName());
            return this.context.getService(reportFileServiceReference);
        }
        return null;
    }
}
